<?php
declare (strict_types = 1);

namespace app\wx\controller;
use app\Request;
use app\wx\model\Copy;
use app\wx\model\EveryTimes;
use liliuwei\think\Jump;
use think\facade\Config;
use think\facade\View;
use app\wx\facade\WxFacade;
use app\wx\model\Wxgroup;
use app\wx\model\Wxnumber;
use think\facade\Cache;
class Index
{
    use Jump;

    /*
     * 获取分组列表
     */
    public function index(Request $request)
    {
        if ($request->isPost()){
            if (!empty($request->param('groupname'))) {
                return WxFacade::getGroup($request->param('groupname'));
            }else{
                 //根据id获取创建的微信分组
                return WxFacade::getGroup();
            }
        }
        return View::fetch();
    }


    /**
     * @param Request $request
     * @return string|void
     * 创建分组
     */
    public function create(Request $request){
        if ($request->isPost()){
            //获取当前id
            $data = $request->param();

            // var_dump($data);exit;
            $user = get_admin_session();
            array_key_exists('status',$data)?$data['status'] = 1:$data['status'] = 0;
            $data['userid'] = $user['id'];
            $wxgropu = new Wxgroup();
            // 查询当前添加的微信分组是否已存在
            $group = $wxgropu::where('groupname',$request->param('groupname'))->find();
            if (!empty($group)) {
                return $this->success('分组已存在');
            }
            $wxgropu->save($data);
            return $this->success('添加分组成功');

        }
        return View::fetch();
    }

    /**
     * @param Request $request
     * @return string|void
     * 添加单个微信和二维码
     */
    public function addwx(Request $request){

        if ($request->isPost()){
            $data = $request->param(['wxnum','wxname','img','gid']);
            $user = get_admin_session();
            $wxnumber = new Wxnumber();
            if ($data['img']==""){
                $saveDate = [
                    'uid' => $user['id'],
                    'gid' =>$data['gid'],
                    'number' => $data['wxnum'],
                    'name'  => $data['wxname']
                ];
            }else{
                $saveDate = [
                    'uid' => $user['id'],
                    'gid' =>$data['gid'],
                    'number' => $data['wxnum'],
                    'name'  => $data['wxname'],
                    'imgurl' => 'storage/' .$data['img']
                ];
            }
            $wxnumber->data($saveDate)->save();
            // 根据提交过来的微信分组gid 删除 在redis中的微信分组gid数据(从而实现更新微信分组，要不然redis还是未更新之前的微信数据)
            $this->delRedisGid($data['gid']);
            return $this->success('添加成功');
            
        }
        View::assign('gid',$request->param('id'));
        return View::fetch();
    }


    /**
     * 获取当前组的微信号
     */
    public function catchOne(Request $request){

       $gid = $request->param('gid');
       $user = get_admin_session();

       $wxnumber = new Wxnumber();
        $data =  $wxnumber->where(['uid'=>$user['id'],'gid'=>$gid])->select()->toArray();
       return lay_msg(0,'success',count($data),$data);
    }

    /**
     * 根据id删除微信号
     * 删除微信号
     */
    public function deleteWx(Request $request){
//        var_dump($request->param());
        $wxnumber = new Wxnumber();
        $res = $wxnumber->where(['id'=>$request->param('id'),'uid'=>$request->param('uid'),'gid'=>$request->param('gid')])->find();
        if ($res){
            //首先删除照片，再删除数据
            $imgUrl =  $res->getData('imgurl');
            if (($imgUrl != "") || (!is_null($imgUrl))){
                try {
                    unlink($imgUrl);
                } catch (\Exception $e) {
                    // 这是进行异常捕获
                    //  return json($e->getMessage());
                }
            }

            $wxnumber->where('id',$request->param('id'))->delete();

             // 根据提交过来的微信分组gid 删除 在redis中的微信分组gid数据(从而实现更新微信分组，要不然redis还是未更新之前的微信数据)
             $this->delRedisGid($request->param('gid'));
            return $this->success('删除成功');
        }
    }


    /**
     * 批量添加微信
     */
    public function addAll(Request $request){

        if ($request->isPost()){

            $gid = $request->param('gid');
            $user = get_admin_session();
            $wx = textareaToStr($request->param('wx'));

            $wxData = array();

            foreach ($wx as $k=>$v){
                $wxData[$k]['uid'] = $user['id'];
                $wxData[$k]['gid'] = $gid;
                $wxData[$k]['number'] = $v;
            }

            $wxnumber = new Wxnumber();
            $wxnumber->saveAll($wxData);

             // 根据提交过来的微信分组gid 删除 在redis中的微信分组gid数据(从而实现更新微信分组，要不然redis还是未更新之前的微信数据)
             $this->delRedisGid($gid);

            return $this->success('添加成功');

        }
        View::assign('gid',$request->param('id'));
        return View::fetch();
    }


    /**
     * 保存微信号和二维码上传
     */
    public function imgSave(Request $request){
        $user = get_admin_session();
        $file = request()->file('file');
        try {
            validate(['file' => [
                'fileSize' => 1048576,
                'fileExt' => 'jpg,png,gif,jpeg',
                'fileMime' => 'image/jpeg,image/png,image/gif',
            ]])->check(['file' => $file]);
            $savename = \think\facade\Filesystem::disk('public')->putFile((string)$user['id'], $file);

            if (!$savename) {
                return json(['', 'code' => 0, 'msg' => '上传失败']);
            }
            return json(['savename' => $savename, 'code' => 1, 'msg' => '上传成功']);
        } catch (ValidateException $e) {
            return $e->getMessage();
        }

    }


    /*
     * 删除分组和分组以下的所有信息
     */
    public function deleteGropu(Request $request){
        //删除该分组下的所有图片
        $wxnumber = new Wxnumber();
        $res = $wxnumber->where(['gid'=>$request->param('id'),'uid'=>$request->param('userid')])->select();
        //分组中存在数据
        if (!$res->isEmpty()){
                $imgurl =array_unique($res->column('imgurl'));
                $imgArray=array();
                foreach ($imgurl as $k=>$v){
                    if (strlen($v) == 0){
                        continue;
                    }else{
                        $str= delStrToStr($v,Config::get('wxCatch.wxDomain').'/');
                    }
                    $imgArray[] = $str;
                }
                foreach ($imgArray as $v){
                    try {
                        unlink($v);
                    } catch (\Exception $e) {
                        // 这是进行异常捕获
                        //  return json($e->getMessage());
                    }
                }
                //删除该分组下的所有信息
                $res = $wxnumber->where(['gid'=>$request->param('id'),'uid'=>$request->param('userid')])->delete();
                if ($res){
                    $wxgroup = new Wxgroup();
                    $wxgroup->where('id',$request->param('id'))->delete();
                    // 根据提交过来的微信分组gid 删除 在redis中的微信分组gid数据(从而实现更新微信分组，要不然redis还是未更新之前的微信数据)
                    $this->delRedisGid($request->param('id'));

                    return $this->success('删除成功');
                }
                 return $this->error('删除失败');
        }

        //分组中没有数据，直接删除该分组

        $wxgroup = new Wxgroup();
        $wxgroup->where('id',$request->param('id'))->delete();

        $this->delRedisGid($request->param('id'));

        return $this->success('删除成功');

    }

    // 禁用/启用微信分组
    public function exchangeStatus(Request $request){
       $wxgroup =  new Wxgroup();
       $res = $wxgroup->where(['id'=>$request->param('id'),'userid'=>$request->param('userid')])->find();
        $res->status = $res['status']?0:1;
        $res->save();
         //  删除存在与redis的微信分组
         $this->delRedisGid($request->param('id'));
        return $this->success('更新成功');
    }

    // 禁用/启用微信号显示
    public function exchangeWxStatus(Request $request){
        $wxnumber = new Wxnumber();
        $res = $wxnumber->where(['id'=>$request->param('id'),'uid'=>$request->param('uid')])->find();
         $res->status = $res['status']?0:1;
         $res->save();
        //  删除存在与redis的微信分组
         $this->delRedisGid($request->param('gid'));
         return $this->success('更新成功');
     }


    /**
     * @param Request $request
     * @return string
     * 获取调用链接
     */
    public function catchUrl(Request $request){
//        var_dump($request->param());
        $user = get_admin_session();
        $wxdy = "<script id=\"a2bcWx\" src=\"".$request->domain()."/wx/wxAndCopy.js?dw=".$user['id']."&gid=".$request->param('id')."&flag=wx\" type=\"text/javascript\" charset=\"utf-8\"></script>";
        View::assign("wxdy",$wxdy);

        $wxCopy = "<script id=\"a2bcWx\" src=\"".$request->domain()."/wx/wxAndCopy.js?dw=".$user['id']."&flag=copy\" type=\"text/javascript\" charset=\"utf-8\"></script>";
        View::assign("wxCopy",$wxCopy);
        
        $wxAndCopy = "<script id=\"a2bcWx\" src=\"".$request->domain()."/wx/wxAndCopy.js?dw=".$user['id']."&gid=".$request->param('id')."&flag=wxcopy\" type=\"text/javascript\" charset=\"utf-8\"></script>";
        View::assign("wxAndCopy",$wxAndCopy);

        return View::fetch();
    }

    // 展现复制次数
    public function showCopy(Request $request){
    //    var_dump($request->param());die;
        $gid = $request->param('id');

        View::assign('gid',$gid);
        return View::fetch();
    }

    // 计算复制次数
    public function wxCopyShow(Request $request){
        $gid = $request->param('id');
        $user = get_admin_session();
        $wxnumber = new Wxnumber();
        $data = $wxnumber->where(['uid'=>$user['id'],'gid'=>$gid])->field('number')->column('number');
        $wx = array_unique($data);


        $copy= new Copy();
        $showWx = $copy->where('user_id',$user['id'])->field('c')->column('c');
        $showTimes =  array_count_values($showWx);

        $everyTimes = new EveryTimes();
        $every = $everyTimes->where('user_id',$user['id'])->column('show_wx');
//        var_dump($every);
        foreach ($every as $k=>$v){
            if ($v==""|| is_null($v)){
                unset($every[$k]);
            }
        }
        $everyWxShow =  array_count_values($every);

        $arr = array();
        foreach($wx as $k=>$v){
            $arr[$k]["wx"] = $v;
            if(!array_key_exists($v,$showTimes)){
                $arr[$k]["times"] = 0;
            }else{
                $arr[$k]["times"] = $showTimes[$v];
            }

            if(!array_key_exists($v,$everyWxShow)){
                $arr[$k]["showTimes"] = 0;
            }else{
                $arr[$k]["showTimes"] = $everyWxShow[$v];
            }
        }
//        var_dump($arr);
        return lay_msg(0,'success',count($arr),$arr);
    }


    
    /**
     * @name: 
     * @Description: 描述：根据微信分组id删除redis的数据
     * @param $gid  微信分组id
     * @return {*}
     * @Date: 2022-04-04 23:09:44
     * @LastEditTime: Do not edit
     * @Route: 
     */    
    public function delRedisGid($gid)
    {
        Cache::store('redis')->delete($gid);
    }



}
